package com.xpec.c4.service.group.transportlayer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.game.utility.GameUtility;
import com.xpec.c4.message.ContextStatus;
import com.xpec.c4.service.contexts.Contexts;
import com.xpec.c4.service.h5server.H5ServerOperations;
import com.xpec.c4.service.module.ModuleName;
import com.xpec.c4.service.module.ServerProperties;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;
import com.xpec.c4.service.module.common.content.SessionContent;
import com.xpec.c4.service.server.ServerOperations;

/**
 * session Contexts 的的异步处理任务
 * 
 * @author lipeilin
 * 
 */
public class ContextsSessionTask implements Runnable {
	private static final Log log = LogFactory.getLog(ContextsSessionTask.class);
	private ContextStatus message;

	public ContextsSessionTask(ContextStatus message) {
		this.message = message;
	}

	@Override
	public void run() {
		GUID sessionID = message.getSessionId();
		switch (message.getStatus()) {
		case ContextStatus.CONTEXT_START:
			Contexts.startSessionContext(sessionID);
			
			// 將session所屬的資訊 加入 Common			
			SessionContent content = new SessionContent();
			content.setIp(message.getClientIp());
			content.setPlatform(message.getLoginPlatform());
			content.setGateway(message.getGateway());
			content.setAgentData(message.getAgentData());

			PlayerCommonInfoManager.getInstance().setSessionContent(sessionID, content);
			break;
		case ContextStatus.CONTEXT_END:
			//斷線處理流程
			
			
			if (log.isInfoEnabled()) {
				log.info("Session Close Log " + GameUtility.getCurMethodName() + " CONTEXT_END START! SessionId = " + ((sessionID == null) ? "null" : sessionID));
			}
			
			if (ServerProperties.isTargetModule(PlayerCommonInfoManager.getInstance().getGatewayBySessionId(sessionID), ModuleName.H5GATEWAY)) {
				H5ServerOperations.disconnectionAllGateWayProcess(sessionID);
			} else {
				ServerOperations.disconnectionAllGateWayProcess(sessionID);
			}
			
			if (log.isInfoEnabled()) {
				log.info("Session Close Log " + GameUtility.getCurMethodName() + " CONTEXT_END END! SessionId = " + ((sessionID == null) ? "null" : sessionID));
			}
			
			Contexts.endSessionContext(message.getSessionId(), message
					.getCloseType());
			break;
		}
	}
}
